#!/usr/bin/perl

#=======================================================================
# git-pa
# File ID: ee782996-282c-11e2-9c05-00c0a8deee11
# [Description]
#
# Character set: UTF-8
# ©opyleft 2012– Øyvind A. Holm <sunny@sunbase.org>
# License: GNU General Public License version 2 or later, see end of 
# file for legal stuff.
#=======================================================================

use strict;
use warnings;
use Getopt::Long;

local $| = 1;

our $Debug = 0;

our %Std = (

    'regexpfile' => "$ENV{'HOME'}/.git-pa-remotes",

);
our %Opt = (

    'all-remotes' => 0,
    'debug' => 0,
    'dry-run' => 0,
    'force' => 0,
    'help' => 0,
    'regexpfile' => $Std{'regexpfile'},
    'verbose' => 0,
    'version' => 0,

);

our $progname = $0;
$progname =~ s/^.*\/(.*?)$/$1/;
our $VERSION = '0.00';

Getopt::Long::Configure('bundling');
GetOptions(

    'all-remotes|a' => \$Opt{'all-remotes'},
    'debug' => \$Opt{'debug'},
    'dry-run|n' => \$Opt{'dry-run'},
    'force|f' => \$Opt{'force'},
    'help|h' => \$Opt{'help'},
    'regexpfile=s' => \$Opt{'regexpfile'},
    'verbose|v+' => \$Opt{'verbose'},
    'version' => \$Opt{'version'},

) || die("$progname: Option error. Use -h for help.\n");

$Opt{'debug'} && ($Debug = 1);
$Opt{'help'} && usage(0);
if ($Opt{'version'}) {
    print_version();
    exit(0);
}

$Opt{'dry-run'} && msg(0, "Note: This is just a simulation.");

=pod

For every remote
    For every regexp in ~/.git-pa-remotes
        List remotes | grep ^remote | grep current regexp
            Push with args
            If the remote is specified in git-pa.allremotes
                Push all
                Push tags

=cut

my @pushremotes = read_regexpfile($Opt{'regexpfile'});

my @cmdline_args = @ARGV;
msg(2, "cmdline_args = '" . join('|', @cmdline_args) . "'");

my $config_allremotes = `git config --get git-pa.allremotes`;
chomp($config_allremotes);
my @allremotes_elem = split(' ', $config_allremotes);
msg(1, 'Will use --all and --tags with the following remotes: ' . join(', ', @allremotes_elem));

my %allremotes = ();
for (@allremotes_elem) {
    $allremotes{$_} = 1;
}

for my $f (`git remote`) {
    chomp($f);
    my $do_push = 0;
    for my $ch (@pushremotes) {
        chomp($ch);
        msg(2, "ch = '$ch'");
        my $pipefp;
        open($pipefp, 'git remote -v |') or die("$progname: git remote -v: Cannot open pipe: $!\n");
        while (my $curr = <$pipefp>) {
            chomp($curr);
            msg(3, "curr = '$curr'");
            if ($curr =~ /^$f\s/ && $curr =~ /$ch/) {
                msg(1, "Found ('$curr' =~ /$ch/)");
                $do_push = 1;
            }
        }
        close($pipefp);
    }
    $Opt{'all-remotes'} && ($do_push = 1);
    if ($do_push) {
        if ($Opt{'force'}) {
            mysystem('git', 'push', '--force', $f, @ARGV);
        } else {
            mysystem('git', 'push', $f, @ARGV);
        }
        if (defined($allremotes{$f})) {
            mysystem('git', 'push', '--all', $f);
            mysystem('git', 'push', '--tags', $f);
        }
    }
}

exit;

sub check_sig {
    my $retval = shift;
    ($retval & 127) && die("\n$progname: Child process interrupted, aborting.\n");
    return(0);
} # check_sig()

sub mysystem {
    # {{{
    my @args = @_;
    print(STDERR "\n");
    msg(0, "Executing '" . join(' ', @args)  . "'");
    $Opt{'dry-run'} || system(@args) && check_sig($?);
    return;
    # }}}
} # mysystem()

sub read_regexpfile {
    # {{{
    my $regexpfile = shift;
    my $fp;
    my @Retval = ();
    open($fp, '<', $regexpfile) || die("$progname: $regexpfile: Could not read regexp file: $!\n");
    while (my $curr = <$fp>) {
        chomp($curr);
        push(@Retval, $curr);
        msg(1, "regexp: $curr");
    }
    return(@Retval);
    # }}}
} # read_regexpfile()

sub print_version {
    # Print program version {{{
    print("$progname v$VERSION\n");
    return;
    # }}}
} # print_version()

sub usage {
    # Send the help message to stdout {{{
    my $Retval = shift;

    if ($Opt{'verbose'}) {
        print("\n");
        print_version();
    }
    print(<<"END");

Usage: $progname [options] [args for git push]

Options:

  -a, --all-remotes
    Push to all local remotes.
  -f, --force
    Use --force when pushing. Overwrites remote branches, be careful.
  -h, --help
    Show this help.
  -n, --dry-run
    Don't really push the branches, simulate only.
  --regexpfile X
    Use regexpfile X instead of the default
    '$Std{'regexpfile'}'.
  -v, --verbose
    Increase level of verbosity. Can be repeated.
  --version
    Print version information.
  --debug
    Print debugging messages.

The 'git-pa.allremotes' configuration option can contain a 
space-separated list of remotes which will also get pushed to using 
'--all' and '--tags'.

END
    exit($Retval);
    # }}}
} # usage()

sub msg {
    # Print a status message to stderr based on verbosity level {{{
    my ($verbose_level, $Txt) = @_;

    if ($Opt{'verbose'} >= $verbose_level) {
        print(STDERR "$progname: $Txt\n");
    }
    return;
    # }}}
} # msg()

sub D {
    # Print a debugging message {{{
    $Debug || return;
    my @call_info = caller;
    chomp(my $Txt = shift);
    my $File = $call_info[1];
    $File =~ s#\\#/#g;
    $File =~ s#^.*/(.*?)$#$1#;
    print(STDERR "$File:$call_info[2] $$ $Txt\n");
    return('');
    # }}}
} # D()

__END__

# Plain Old Documentation (POD) {{{

=pod

=head1 NAME



=head1 SYNOPSIS

 [options] [file [files [...]]]

=head1 DESCRIPTION



=head1 OPTIONS

=over 4

=item B<-h>, B<--help>

Print a brief help summary.

=item B<-v>, B<--verbose>

Increase level of verbosity. Can be repeated.

=item B<--version>

Print version information.

=item B<--debug>

Print debugging messages.

=back

=head1 BUGS



=head1 AUTHOR

Made by Øyvind A. Holm S<E<lt>sunny@sunbase.orgE<gt>>.

=head1 COPYRIGHT

Copyleft © Øyvind A. Holm E<lt>sunny@sunbase.orgE<gt>
This is free software; see the file F<COPYING> for legalese stuff.

=head1 LICENCE

This program is free software: you can redistribute it and/or modify it 
under the terms of the GNU General Public License as published by the 
Free Software Foundation, either version 2 of the License, or (at your 
option) any later version.

This program is distributed in the hope that it will be useful, but 
WITHOUT ANY WARRANTY; without even the implied warranty of 
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along 
with this program.
If not, see L<http://www.gnu.org/licenses/>.

=head1 SEE ALSO

=cut

# }}}

# vim: set fenc=UTF-8 ft=perl fdm=marker ts=4 sw=4 sts=4 et fo+=w :
